#!/bin/sh
#
# Copyright (c) 2016 Lucky Byte, Inc.
#
# Summary : 数据库备份
#
# Author : xiaohu <xiaohu@lucky-byte.com>
# Since  : 2016.12.15
#
# History
#  * 2016.12.31 : 清理 pay_p2_orders 表，增加 vacuum 语句
#
today=`date +%Y%m%d`

trlist_bakfile="/home/backup/trlist-$today.bak"
p2_order_bakfile="/home/backup/p2_order-$today.bak"

# 不能覆盖存在的文件
if [ -f $trlist_bakfile ]; then
    echo "备份文件 $trlist_bakfile 已经存在，不能覆盖."
    exit 1
fi
if [ -f $p2_order_bakfile ]; then
    echo "备份文件 $p2_order_bakfile 已经存在，不能覆盖."
    exit 1
fi

psql -U xtpt -h 127.0.0.1 LUCKPAY -w  <<EOF
-- 清理 pay_trlist_hist
copy (
    select * from pay_trlist_hist where sys_time < (
        '${today}'::date - interval '3 months'
    )
) to '$trlist_bakfile' delimiter ',';

delete from pay_trlist_hist where sys_time < (
    '${today}'::date - interval '3 months'
);
vacuum pay_trlist_hist;

-- 清理 pay_p2_orders
copy (
    select * from pay_p2_order_hist where sys_time < (
        '${today}'::date - interval '3 months'
    )
) to '$p2_order_bakfile' delimiter ',';

delete from pay_p2_order_hist where sys_time < (
    '${today}'::date - interval '3 months'
);
vacuum pay_p2_order_hist;
EOF

if [ $? -eq 0 ]; then
    echo "备份历史数据成功."
else
    echo "备份历史数据失败."
fi
